package com.warmheart.controller.user;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.controller.BaseController;
import com.warmheart.base.page.PageInfo;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.OperatorUtil;
import com.warmheart.core.util.ParamMapUtil;
import com.warmheart.entity.user.UserBase;
import com.warmheart.service.user.IUserBaseService;

/**
 * 
 * @ClassName: UserBaseController
 * @Description: 用户控制器
 * @author ZhangJianyang
 * @date 2025年06月16日 下午13:05:35
 *
 */
@RestController
@RequestMapping("/user/userBase")
public class UserBaseController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserBaseController.class);

    // 注入用户service
    @Autowired(required = false)
    private IUserBaseService userBaseService;

    /**
     * 
     * @Title: listData
     * @Description: 查询用户列表数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/listData")
    public CommonResult<Map<String, Object>> listData(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();

        // 参数对象
        UserBase userBase = new UserBase();

        // 每页记录数
        Integer pageSize = ParamMapUtil.getInteger(jsonMap, "pageSize");
        if (pageSize == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "每页记录数不能为空");
        }
        if (pageSize <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "每页记录数必须大于0");
        }
        userBase.setPageSize(pageSize);

        // 页码
        Integer pageId = ParamMapUtil.getInteger(jsonMap, "pageId");
        if (pageId == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "页码不能为空");
        }
        if (pageId <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "页码必须大于0");
        }
        userBase.setPageId(pageId);

        // 查询列表
        PageInfo<UserBase> pageInfo = this.userBaseService.queryByList(userBase);

        List<UserBase> dataList = pageInfo.getData();
        Map<String, Object> pageMap = new HashMap<String, Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (dataList != null && dataList.size() > 0) {

            // 整理返回数据
            for (UserBase tempData : dataList) {
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("id", tempData.getId());
                tempMap.put("realName", tempData.getRealName());
                tempMap.put("email", tempData.getEmail());
                tempMap.put("phone", tempData.getPhone());
                tempMap.put("department", tempData.getDepartment());
                tempMap.put("position", tempData.getPosition());
                tempMap.put("state", tempData.getState());
                tempMap.put("lastLogin", tempData.getLastLogin());
                tempMap.put("cstCreate", tempData.getCstCreate());
                mapList.add(tempMap);
            }
        }
        pageMap.put("dataList", mapList);
        pageMap.put("rowCount", pageInfo.getPager().getRowCount());
        pageMap.put("pageCount", pageInfo.getPager().getPageCount());
        resultMap.put("pageMap", pageMap);
        return CommonResult.success("分页查询用户数据成功", resultMap);
    }

    /**
     * 
     * @Title: update
     * @Description: 修改用户数据进入页面
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/update")
    public CommonResult<Map<String, Object>> update(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();

        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户ID不可为空");
        }

        // 校验是否存在
        UserBase checkUserBase = userBaseService.queryById(id);
        if (checkUserBase == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户不存在");
        }
        Map<String, Object> tempMap = new HashMap<String, Object>();
        tempMap.put("id", checkUserBase.getId());
        tempMap.put("realName", checkUserBase.getRealName());
        tempMap.put("email", checkUserBase.getEmail());
        tempMap.put("phone", checkUserBase.getPhone());
        tempMap.put("department", checkUserBase.getDepartment());
        tempMap.put("position", checkUserBase.getPosition());
        tempMap.put("state", checkUserBase.getState());
        tempMap.put("lastLogin", checkUserBase.getLastLogin());
        tempMap.put("cstCreate", checkUserBase.getCstCreate());
        resultMap.put("dataMap", tempMap);
        return CommonResult.success("获取用户数据成功", resultMap);
    }

    /**
     * 
     * @Title: addSave
     * @Description: 添加保存用户数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @RequestMapping("/addSave")
    public CommonResult<Map<String, Object>> addSave(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 数据对象
        UserBase userBase = new UserBase();

        // 真实姓名
        String realName = ParamMapUtil.getString(jsonMap, "realName");
        if (StringUtils.isNotBlank(realName)) {
            userBase.setRealName(realName);
        }

        // 邮箱
        String email = ParamMapUtil.getString(jsonMap, "email");
        if (StringUtils.isNotBlank(email)) {
            userBase.setEmail(email);
        }

        // 手机号
        String phone = ParamMapUtil.getString(jsonMap, "phone");
        if (StringUtils.isNotBlank(phone)) {
            userBase.setPhone(phone);
        }

        // 部门
        String department = ParamMapUtil.getString(jsonMap, "department");
        if (StringUtils.isNotBlank(department)) {
            userBase.setDepartment(department);
        }

        // 职位
        String position = ParamMapUtil.getString(jsonMap, "position");
        if (StringUtils.isNotBlank(position)) {
            userBase.setPosition(position);
        }

        // 是否激活
        String state = ParamMapUtil.getString(jsonMap, "state");
        if (StringUtils.isNotBlank(state)) {
            userBase.setState(state);
        }

        // 最后登录时间
        String lastLogin = ParamMapUtil.getString(jsonMap, "lastLogin");
        if (StringUtils.isNotBlank(lastLogin)) {

            // 最后登录时间
            Date lastLoginRealValue = new SimpleDateFormat("yyyy-MM-dd").parse(lastLogin);
            userBase.setLastLogin(lastLoginRealValue);
        }

        try {
            OperatorUtil.addOper(userBase);
            userBaseService.add(userBase);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("添加用户失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "添加用户失败");
        }

        return CommonResult.success("添加用户成功");
    }

    /**
     * 
     * @Title: updateSave
     * @Description: 修改保存用户数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @RequestMapping("/updateSave")
    public CommonResult<Map<String, Object>> updateSave(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);

        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户ID不可为空");
        }

        // 是否存在校验
        UserBase checkUserBase = userBaseService.queryById(id);
        if (checkUserBase == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户不存在");
        }

        // 真实姓名
        String realName = ParamMapUtil.getString(jsonMap, "realName");
        if (StringUtils.isNotBlank(realName)) {
            checkUserBase.setRealName(realName);
        }

        // 邮箱
        String email = ParamMapUtil.getString(jsonMap, "email");
        if (StringUtils.isNotBlank(email)) {
            checkUserBase.setEmail(email);
        }

        // 手机号
        String phone = ParamMapUtil.getString(jsonMap, "phone");
        if (StringUtils.isNotBlank(phone)) {
            checkUserBase.setPhone(phone);
        }

        // 部门
        String department = ParamMapUtil.getString(jsonMap, "department");
        if (StringUtils.isNotBlank(department)) {
            checkUserBase.setDepartment(department);
        }

        // 职位
        String position = ParamMapUtil.getString(jsonMap, "position");
        if (StringUtils.isNotBlank(position)) {
            checkUserBase.setPosition(position);
        }

        // 是否激活
        String state = ParamMapUtil.getString(jsonMap, "state");
        if (StringUtils.isNotBlank(state)) {
            checkUserBase.setState(state);
        }

        // 最后登录时间
        String lastLogin = ParamMapUtil.getString(jsonMap, "lastLogin");
        if (StringUtils.isNotBlank(lastLogin)) {

            // 最后登录时间
            Date lastLoginRealValue = new SimpleDateFormat("yyyy-MM-dd").parse(lastLogin);
            checkUserBase.setLastLogin(lastLoginRealValue);
        }

        try {
            OperatorUtil.updateOper(checkUserBase);
            userBaseService.updateIncludeAll(checkUserBase);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("修改用户失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "修改用户失败");
        }

        return CommonResult.success("修改用户成功");
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除用户数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/delete")
    public CommonResult<Map<String, Object>> delete(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户ID不可为空");
        }

        // 是否存在校验
        UserBase checkUserBase = userBaseService.queryById(id);
        if (checkUserBase == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户不存在");
        }

        try {
            userBaseService.deleteById(checkUserBase.getId());
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除用户失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除用户失败");
        }

        return CommonResult.success("删除用户成功");
    }
}
